<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\warehouse\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\warehouse\model\WareHouse as WareHouseModel;
use app\goods\model\GoodsClass as GoodsClassModel;
use app\warehouse\model\Stock as StockModel;
use app\goods\model\Size as SizeModel;
use app\goods\model\Color as ColorModel;
use think\Db;

/**
 * 库存管理控制器
 * @package app\warehouse\controller
 */
class Stock extends Admin
{
    /**
     * 库存查询
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        $pagetitle="库存查询";

        $where=[];
        if(!empty($_GET['warehouseid'])) $where['warehouseid']=$_GET['warehouseid'];
        if(!empty($_GET['artno'])) {
            $artno=GoodsClassModel::where('classid',$_GET['artno'])->value('artno');
            $where['artno']=$artno;
        }
        if(!empty($_GET['storeid'][0])) $where['storeid']=$_GET['storeid'][0];

    	$data_list = Db::name('goods_stock')->where($where)->order(['skuid desc'])->paginate();
        // 分页数据
        $page = $data_list->render();

        $class_list = GoodsClassModel::where('status','1')->column('classid,artno');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('mix')
            ->setTableName('goods_stock')
            ->setPrimaryKey("stockid")
            ->addSelect('warehouseid', '仓库','',WareHouseModel::getAllList(['status'=>1,'isdel'=>0]),!empty($where['warehouseid'])?$where['warehouseid']:'')
            ->addSelect('artno', '款类','', $class_list,!empty($_GET['artno'])?$_GET['artno']:'')
            ->addSelect('storeid','店铺','','',!empty($where['storeid'])?$where['storeid']:'','ajax','',['url'=>url('product/product/shoplist'),'datakey'=>'id','dataname'=>'name'])
            ->addBtn('<button type="submit" class="btn  btn-primary btn-rounded">确定搜索</button>')
            ->hideBtn('submit,back')
            ->layout(['warehouseid'=>3,'artno'=>3,'storeid'=>3,'form_group_btnGroup'=>2])
            ->setPageTitle($pagetitle) // 设置页面标题
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['goodsno', '货品编号','','','','fix-table-td'],
                ['artno', '款号'],
                ['typename', '类别'],
                ['brandname', '品牌名'],
                ['unitname', '单位'],
                ['colorname', '颜色'],
                ['sizename', '尺寸'],
                ['totalnum', '总库存'],
                ['holdnum', '保留'],
                ['waitnum', '可用'],
                ['frozennum', '冻结'],
                ['waitdeliverynum', '待发货'],
                ['occupynum', '订购量'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('custom', ['title' => '二维查询', 'icon' => 'fa fa-fw fa-slack', 'href'=> url('two_dimensional'), 'class' => 'btn btn-info'])
            ->addRightButton('custom', ['href' => url('frozen',['id' => '__id__']), 'icon' => 'fa fa-fw fa-times-circle-o', 'title' => '冻结'],true)
            ->addRightButton('custom', ['href' => url('hold',['id' => '__id__']), 'icon' => 'fa fa-fw fa-ban', 'title' => '保留'],true)
            ->setRowList($data_list)
            ->setPages($page) // 设置分页数据
            ->isAjax(false)
            ->setFormMethod('get')
            ->fetch(); // 渲染模板
    }

    public function two_dimensional(){
       $where=[];
        if(!empty($_GET['shopid'])) $where['storeid']=$_GET['shopid'];
        if(!empty($_GET['warehouseid'])) $where['warehouseid']=$_GET['warehouseid'];
        $goodsclass=$colordata=$sizedata=[];
        if(!empty($_GET['artno'])) {
            $goodsclass=GoodsClassModel::where('classid',$_GET['artno'])->field('artno,sizebox,colorbox')->find();
            $where['artno']=$goodsclass['artno'];
        
            $sizedata=SizeModel::where(['status'=>1,'sizeid'=>['in',$goodsclass['sizebox']]])->order('sort asc,sizeid asc')->select();
            $colordata=ColorModel::where(['status'=>1,'colorid'=>['in',$goodsclass['colorbox']]])->order('sort asc,colorid asc')->select();
            if(!empty($where)){
                foreach ($colordata as $key => $value) {
                    # code...
                    $stockdata=[];
                    foreach ($sizedata as $k => $val) {
                        $num=StockModel::where(['sizename'=>$val['name'],'colorname'=>$value['name']])->where($where)->sum('waitnum');
                        $stockdata[$k]['num']=!empty($num)?$num:'-';
                    }
                    $colordata[$key]['stockdata']=$stockdata;
                }
            }else{
                $colordata=[];
            }
        }
        $this->assign("colordata",$colordata);
        $this->assign("sizedata",$sizedata);

        
        $class_list = GoodsClassModel::where('status','1')->field('classid,artno')->select();
        $this->assign("typedata",$class_list);
        $warehousedata=WareHouseModel::where(['status'=>1,'isdel'=>0])->field('warehouseid,warehousename')->select();
        $this->assign("warehousedata",$warehousedata);
        $shopdata = \think\Loader::model('app\shop\model\Shop')->getAllShop(['is_enable' => '1','status' => '1']);
        $this->assign('shopdata',$shopdata);
        return $this->fetch(); // 渲染模板
    }

    public function frozen($id=null){
        $id === null && $this->error('参数错误');
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        return ZBuilder::make('form')
            ->setPageTitle('冻结') // 设置页面标题
            ->setUrl(url('dofrozen'))
            ->addHidden('stockid',$id)
            ->addFormItems([ // 批量添加表单项
                 ['number', 'frozennum', '冻结数量'],
            ])
            ->layout(['text'=>3])
            ->fetch();
    }
    public function dofrozen(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            $data['stockid'] === null && $this->error('参数错误');
            if(intval($data['frozennum'])<=0||$data['frozennum']===null){
                $this->error('请输入冻结数量');
            }

            $stockdata=StockModel::find($data['stockid']);
            if($stockdata['waitnum']<$data['frozennum']) $this->error('可用库存不足');

            if ($menu = StockModel::frozenstock($data['stockid'],$data['frozennum'])) {
                return $this->success('冻结成功', null, ['_parent_reload'=>1]);
            } else {
                return $this->error('冻结失败');
            }
        }
    }
    
    public function hold($id=null){
        $id === null && $this->error('参数错误');
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        return ZBuilder::make('form')
            ->setPageTitle('保留') // 设置页面标题
            ->setUrl(url('dohold'))
            ->addHidden('stockid',$id)
            ->addFormItems([ // 批量添加表单项
                 ['number', 'holdnum', '冻结数量'],
            ])
            ->layout(['text'=>3])
            ->fetch();
    }
    public function dohold(){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            $data['stockid'] === null && $this->error('参数错误');
            if(intval($data['holdnum'])<=0||$data['holdnum']===null){
                $this->error('请输入保留数量');
            }

            $stockdata=StockModel::find($data['stockid']);
            if($stockdata['waitnum']<$data['holdnum']) $this->error('可用库存不足');

            if ($menu = StockModel::holdstock($data['stockid'],$data['holdnum'])) {
                return $this->success('保留成功', null, ['_parent_reload'=>1]);
            } else {
                return $this->error('保留失败');
            }
        }
    }

    /**
     * 库存变动日志
     * @author 陈梦晨 <2391157750@qq.com>
     * @return mixed
     */
    public function log()
    {
       // 查询
        $map = $this->getMap();        
        // 排序
        $order = $this->getOrder('logid desc');
        // 数据列表
        $data_list = Db::name("goods_stock_log")->where($map)->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();
        $css = <<<EOF
           <style>
                .w20{width:10%}
                .w20{width:20%}
                .w50{width:50%}
           </style>
EOF;
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("库存变动日志") // 设置页面标题
            ->setTableName('goods_stock_log')
            ->setPrimaryKey("logid")
            ->addTimeFilter('create_time')
            ->addColumns([ // 批量添加数据列
                ['logid', '编号','','','','w10'],
                ['content', '详情','','','','w50'],
                ['num', '变动数量','','','','w10'],
                ['create_time', '操作时间','datetime']
            ])
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->setExtraCss($css)
            ->fetch(); // 渲染模板
    }
}